<?php

/*
 * Copyright (C) 2014 koodo@qq.com.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

/**
 * Wshop main Class
 */
class App {

    // 路径分割 win下\ linux下/
    const DIR_SEP = DIRECTORY_SEPARATOR;

    // Singleton instance
    protected static $_instance = NULL;
    public $Controller = NULL;

    /**
     * init wechat application
     * @global type $config
     */
    public function init() {
        // 预加载模块
        $this->modulePreload();
    }

    /**
     * 模块预加载
     * @global type $config
     */
    private function modulePreload() {
        global $config;
        foreach ($config->preload as $_preload) {
            ClassLoader::loadModuleFile($_preload);
        }
        // appid
        setcookie("appid", APPID, time() + 3600);
    }

    /**
     * get App Class instance
     * @return $_instance
     */
    public static function getInstance() {
        if (!self::$_instance instanceof self) {
            self::$_instance = new App();
        }
        return self::$_instance;
    }

    /**
     * 
     * @param type $QueryString
     * @return Object QueryObject
     */
    private function packQueryString($QueryString) {
        if (!empty($QueryString)) {
            $QueryObject = new stdClass();
            $QueryString = split('&', $QueryString);
            foreach ($QueryString as $r) {
                $r = split('=', $r);
                if (count($r) == 2) {
                    $QueryObject->$r[0] = $r[1];
                }
            }
            return $QueryObject;
        } else {
            return NULL;
        }
    }

    /**
     * action转换
     * @param type $config
     * @param type $Controller
     * @param type $Action
     * @return type
     */
    private function getAction($config, $Controller, $Action) {
        if ($Action == "") {
            if (array_key_exists($Controller, $config->defaultAction)) {
                return $config->defaultAction[$Controller];
            } else {
                return 'Index';
            }
        } else {
            // Action&querystring
            if (strstr($Action, "&")) {
                return substr($Action, 0, strpos($Action, "&"));
            }
            return $Action;
        }
    }

    /**
     * @global type $config
     * parse http request
     */
    public function parseRequest() {
        global $config;
        // Route the Controller and queryString
        $URI = str_replace($config->shoproot . 'index.php', '', $_SERVER["REQUEST_URI"]);
        $URI = str_replace('/?/', '/', $URI);
        $URI = preg_replace('/\/\?\/$/', '', $URI);
        $URI = str_replace($config->shoproot, '/', $URI);
        $URI = str_replace('index.php', '', $URI);
        $URI = str_replace('?', '', $URI);
        $URI = split('/', $URI);
        
        $RouteParam = new stdClass();
        
        if (isset($GLOBALS['controller'])) {
            $RouteParam->controller = $GLOBALS['controller'];
            $Action = $this->getAction($config, $RouteParam->controller, $GLOBALS['action']);
        } else {
            if ($URI[1] == "" || strpos($URI[1], '=')) {
                $RouteParam->controller = $config->default_controller;
                if (strpos($URI[1], '=')) {
                    $RouteParam->queryString = $URI[1];
                }
            } else {
                $RouteParam->controller = $URI[1];
                $RouteParam->queryString = isset($URI[3]) ? $URI[3] : '';
            }
            $Action = $this->getAction($config, $RouteParam->controller, $URI[2]);
            $RouteParam->action = $Action;
        }
        
        #var_dump($RouteParam);
        #return;

        // 加载控制器 todo exception
        ClassLoader::loadModuleFile($RouteParam->controller);
        $Controller = new $RouteParam->controller($RouteParam->controller, $Action, $RouteParam->queryString);
        // 注册当前URI
        $Controller->uri = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $Controller->uri = $URI = preg_replace('/\/\?\/$/', '', $Controller->uri);
        # echo $Controller->uri;
        // 回调根目录
        $Controller->root = "http://" . $_SERVER['HTTP_HOST'] . $config->shoproot;
        
        // 调用对应方法
        $Controller->$Action($this->packQueryString($RouteParam->queryString));
        $this->Controller = $Controller;
    }

}
